package com.wy.framework.utils.pagenation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;

import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.dao.IDataBaseDao;

public class CurrentPageUtils {
	
	/**
	 * 
	 * Function Name               pageUtils                                   
	 * @param dataBaseDao
	 * @param sqlKey
	 * @param pageSize
	 * @param pageNum
	 * @return          		             
	 * @throws Exception 
	 * @description 分页工具
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-4-8 上午9:42:38           黄忠                     Initial
	 **********************************************************************
	 */
	@SuppressWarnings({ "unchecked", "unused" })
	public static List<Map> pageUtils(IDataBaseDao dataBaseDao, String sqlKey, Integer pageSize, Integer pageNum, List params) throws Exception	{
		List list = new ArrayList();
		Map map = new HashMap();
		
		if(params == null) {
			params = new ArrayList();
		}
		
		String sql= getSql(sqlKey);
		
	
		
		try {
			String sqlForCount = "select count(*) from ( " + sql + " ) ";
			Integer totalNum = dataBaseDao.getJdbcTemplate().queryForObject(sqlForCount,params.toArray(), Integer.class);
			map.put("total", totalNum);
			
			int maxMath=pageNum*pageSize;
			int minMath=pageNum*pageSize-pageSize+1;
			params.add(maxMath);
			params.add(minMath);
			
			String dataSql = " select * from (select a.*, rownum rn from ( " + sql + " ) a where rownum <= ? ) where rn >=? "; 
			map.put("rows",  dataBaseDao.getJdbcTemplate().queryForList(dataSql,params.toArray()));
			list.add(map);
		} catch (DataAccessException e) {
			if (params == null) {
				throw new ErrorSqlException("JDBC 执行查询发生错误,Sqlkey=" + sqlKey
						+ " 传入参数：null" + e.getMessage(), e);
			} else {
				throw new ErrorSqlException("JDBC 执行查询发生错误,Sqlkey=" + sqlKey
						+ " 传入参数：" + params.toString() + e.getMessage(), e);
			}
		}
		
		return list;
		
	} 
	
	/**
	 * 
	 * Method Description:根据key值获取sql语句
	 * 
	 * @param:String key
	 * @return:String sql
	 */
	public static String getSql(String key) {
		CacheManager cacheManager = CacheManager.getInstance();
		Cache cacheSql = cacheManager.getCache("CacheSql");
		synchronized (cacheSql) {
			return (String) cacheSql.get(key).getValue();
		}
	}

}
